import { ref } from "vue";

interface ButtonTypes {
  key?: string;
  disabled?: boolean;
  [key: string]: any;
}

export const useButtonStateManager = () => {
  const buttonList = ref<ButtonTypes[]>([]);

  const set = (state: boolean = true): void => {
    buttonList.value.forEach((item) => {
      item.disabled = state;
    });
  };

  /**
   * 获取按钮列表
   * @returns
   */
  const getButtonList = (): ButtonTypes[] => {
    return buttonList.value;
  };

  /**
   * 设置按钮列表
   * @param val 按钮列表
   */
  const setButtonList = (val: ButtonTypes[] | any[]): void => {
    buttonList.value = val;
  };

  /**
   * 禁用所有按钮
   */
  const lockStateAll = (): void => {
    set();
  };

  /**
   * 解锁所有按钮
   */
  const unLockStateAll = (): void => {
    set(false);
  };

  /**
   * 根据默认字段控制按钮状态
   * @param val 需要禁用的按钮列表
   */
  const lockState = (val: string[]): void => {
    unLockStateAll();
    val.forEach((item) => {
      const result = buttonList.value.find((button) => button.key === item);
      result && (result.disabled = true);
    });
  };

  /**
   * 根据默认字段控制按钮状态
   * @param val 需要解锁的按钮列表
   */
  const unLockState = (val: string[]): void => {
    lockStateAll();
    val.forEach((item) => {
      const result = buttonList.value.find((button) => button.key === item);
      result && (result.disabled = false);
    });
  };

  /**
   * 根据自定义字段禁用按钮
   * @param val 需要禁用的按钮列表
   * @param key 自定义字段
   */
  const lockStateByKey = (val: ButtonTypes[], key: keyof ButtonTypes): void => {
    unLockStateAll();
    val.forEach((item) => {
      const result = buttonList.value.find((button) => button[key] === item[key]);
      result && (result.disabled = true);
    });
  };

  /**
   * 根据自定义字段取消禁用按钮
   * @param val 需要解锁的按钮列表
   * @param key 自定义字段
   */
  const unLockStateByKey = (val: ButtonTypes[], key: keyof ButtonTypes): void => {
    lockStateAll();
    val.forEach((item) => {
      const result = buttonList.value.find((button) => button[key] === item[key]);
      result && (result.disabled = false);
    });
  };

  return {
    getButtonList,
    setButtonList,
    lockStateAll,
    unLockStateAll,
    lockState,
    unLockState,
    lockStateByKey,
    unLockStateByKey
  };
};
